package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import util.DBUtil;

public class Page2 {

	public static void main(String[] args) {
		// 按照学生的入学日期来分页
		final int pageSize = 20;

		Scanner sc = new Scanner(System.in);
		System.out.println("你要查询第几页：");
		int pageNo = sc.nextInt();
		// 计算起点
		int start = (pageNo - 1) * pageSize;
		int end = start + pageSize;// 最后
		String sql = "select * from student order  by birthday desc";
		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// >》》》》》获得了分页的数据

			ps = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			// 设置获取结果集的最大行数>>>
			ps.setMaxRows(end);
			rs = ps.executeQuery();
			if (start > 0)
				rs.absolute(start);// 直接跳到起点之前
			while (rs.next()) {
				System.out.println(rs.getInt("stuno") + ","
						+ rs.getString("sname"));
			}
			DBUtil.close(rs);
			DBUtil.close(ps);
			String sql2 = "select count(*) from student";
			ps = con.prepareStatement(sql2);
			rs = ps.executeQuery();
			int total = 0;
			if (rs.next()) {
				total = rs.getInt(1);
			}
			int pages = (int) Math.ceil(total * 1.0 / pageSize);
			System.out.printf("总有%d条，可分为 %d页\n", total, pages);
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			DBUtil.closeAll(rs, ps, con);
		}

	}

}
